#!/bin/bash

Server_ip="IP"

User_name="USERNAME"

Pass="PASSWORD"

Uuid="509c929ed41fa781"

Download_Dir=$(cd `dirname $0`; pwd)

Date=$(date +%F)

File_name="gui-config_${Date}.json"

Last_file="Lastfile"

Mail_list=("76439984@qq.com" "19122892@qq.com" "373562007@qq.com" "860659618@qq.com" "8440632@qq.com" "379844198@qq.com" "836464800@qq.com" "591649068@qq.com")
#Mail_list=("76439984@qq.com")

Log_File="${Download_Dir}/check.log"



web_check_Times=0
while ((web_check_Times < 3)); do
        check_date=`date "+%F %H:%M:%S"`
        curl -I -s "http://${Server_ip}/api_android.php?do=login&u=${User_name}&p=${Pass}&uuid=${Uuid}" | grep 'HTTP/1.1 200 OK' && break || ((web_check_Times++))

        ((${web_check_Times} == 3)) && echo '梯子手机接口无法访问'  | mutt -s "梯子手机接口无法访问" "76439984@qq.com" && \
        echo ${check_date} '梯子手机接口无法访问' >> ${Log_File} && \
        exit

        sleep 5
done

Config=$(curl -s "http://${Server_ip}/api_android.php?do=login&u=${User_name}&p=${Pass}&uuid=${Uuid}" || exit )

declare -a Server_List

Server_list=($(echo ${Config} | awk -v RS=',' -v ORS="\n" '{print $0}' | grep -P "ip|method|area" | sed -e 's/"ip"/"server"/g' -e 's/area/remarks/g'))
# echo ${Server_list[@]}

Sspass=$(echo ${Config} | awk -v RS=',' -v ORS="\n" '{print $0}' | awk -F: /sspass/'{print $2}')
# echo ${Sspass}

Ssport=$(echo ${Config} | awk -v RS=',' -v ORS="\n" '{print $0}' | awk -F: /ssport/'{print $2}')
# echo ${Ssport}

#get the mob list file
echo ${Server_list[@]} | awk -v SSPASS=${Sspass} -v SSPORT=${Ssport} 'BEGIN{print "'{'\n  \"configs\" : '['"}{for(i=1;i<=NF;i=i+3){print "    '{' \n     " $(i+1) ",\n     " "\"server_port\":"SSPORT",\n     " "\"password\":"SSPASS",\n     " $(i+2) ",\n     " $i ",\n     \"auth\":false \n    '},'" }}END{print "  ], \n\"index\" : 12,\n\"global\" : false,\n\"enabled\" : true,\n\"shareOverLan\" : false,\n\"isDefault\" : false}\n"}' \
> "${Download_Dir}"/"${File_name}"

#get the mob list country
List_country=$(echo ${Server_list[@]} | awk '{for(i=1;i<=NF;i=i+3){print $(i+1)"\n"$(i+2)"\n"$i"\n---------------------"}}')

(( $(grep -c "server_port" "${Download_Dir}"/"${File_name}") == 0 )) && (echo "`date "+%F %H:%M:%S"` 接口获取配置失败" >> ${Log_File};echo "`date "+%F %H:%M:%S"` 手机接口获取配置失败" |mutt -s "手机接口获取配置失败" "76439984@qq.com";exit)

diff "${Download_Dir}"/"${File_name}" "${Download_Dir}"/"${Last_file}" 

if [ $? -eq 0 ];then
	echo "`date "+%F %H:%M:%S"` 配置文件没有变化,不发邮件" >> ${Log_File}
	exit
else
	\cp "${Download_Dir}"/"${File_name}" "${Download_Dir}"/"${Last_file}"
	echo -e "${Date}一份来自手机接口的梯子配置文件,你懂的,文明看球....\n ${List_country}" | mutt -s "${Date}一份来自手机接口的梯子配置文件" ${Mail_list[*]} -a "${Download_Dir}"/"${File_name}" || \
	echo "${Log_File} mail fail" >> ${Log_File}
fi


